package edu.geektime.jiangfan.chapter01;

import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 姜帆
 * 学号:G20210579090057
 */
public class MyClassLoader extends ClassLoader {

    public static void main(String[] args) {
        try {
            Class<?> helloClass = new MyClassLoader().findClass("Hello");
            Method helloMethod = helloClass.getMethod("hello");
            helloMethod.invoke(helloClass.newInstance());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] bytes = readByte();
        // 字节解码
        return defineClass(name,decode(bytes),0,bytes.length);
    }

    private byte [] decode (byte [] bytes) {
        for (int i = 0; i < bytes.length ; i++) {
           bytes[i] = (byte) ~ bytes[i];
        }
        return bytes;
    }

    private byte[] readByte() {
        byte [] bytes = null;
        try(InputStream ins = MyClassLoader.class.getClassLoader().getResourceAsStream("Hello.xlass")){
            bytes =new byte[ins.available()];
            ins.read(bytes,0, bytes.length);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
        return bytes;
    }

}